import { Directive, Input, Output, ElementRef, Renderer2, Inject, SimpleChanges, OnChanges, EventEmitter } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Directive({
  selector: '[wfClickOutside]'
})
export class ClickOutsideDirective implements OnChanges {
  @Input() bindFlag = false;
  @Output() clickOutSide = new EventEmitter<void>();

  private handleClick!: () => void;

  constructor(
    private el: ElementRef,
    private rd: Renderer2,
    @Inject(DOCUMENT) private doc: Document
  ) { }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.bindFlag && !changes.bindFlag.firstChange) {
      if (this.bindFlag) {
        this.handleClick = this.rd.listen(this.doc, 'click', evt => {
          const target = evt.target;
          const isContain = this.el.nativeElement.contains(target);
          if (!isContain) {
            this.clickOutSide.emit(target);
          }
        });
      } else {
        this.handleClick();
      }
    }
  }
}
